package com.mjt.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mjt.admin.model.RespDataBean;
import com.mjt.admin.pojo.Customer;
import com.mjt.admin.mapper.CustomerMapper;
import com.mjt.admin.query.CustomerQuery;
import com.mjt.admin.service.ICustomerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mjt.admin.utils.AssertUtil;
import com.mjt.admin.utils.StringUtil;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

/**
 * <p>
 * 客户表 服务实现类
 * </p>
 *
 * @author 莫某人
 * @since 2021-11-01
 */
@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements ICustomerService {

    @Override
    public RespDataBean<Customer> customerList(CustomerQuery customerQuery) {
        IPage<Customer> page=new Page<Customer>(customerQuery.getPage(),customerQuery.getLimit());

        page=this.baseMapper.selectPage(page,new QueryWrapper<Customer>().eq("is_del",0));


        return new RespDataBean<Customer>(0,"查询成功",page.getRecords(),page.getTotal());
    }

    @Override
    public void saveCustomer(Customer customer) {

        Customer customerTemp=this.getByName(customer.getName());
        AssertUtil.isTrue(StringUtil.isEmpty(customer.getName()),"客户名称不能为空！");
        AssertUtil.isTrue(customerTemp!=null,"客户名称已存在");
        AssertUtil.isTrue(StringUtil.isEmpty(customer.getContact()),"联系人不能为空！");
        AssertUtil.isTrue(StringUtil.isEmpty(customer.getNumber()),"联系电话不能为空！");
        AssertUtil.isTrue(StringUtil.isEmpty(customer.getAddress()),"联系地址不能为空！");



        AssertUtil.isTrue(!this.save(customer),"添加失败");
    }

    @Override
    public Customer getByName(String name) {
       return this.baseMapper.selectOne(new QueryWrapper<Customer>()
               .eq("is_del",0).eq("name",name));
    }

    @Override
    public void updateCustomer(Customer customer) {

        Customer customerTemp=this.getByName(customer.getName());
        AssertUtil.isTrue(StringUtil.isEmpty(customer.getName()),"客户名称不能为空！");
        AssertUtil.isTrue(customerTemp!=null,"客户名称已存在");
        AssertUtil.isTrue(StringUtil.isEmpty(customer.getContact()),"联系人不能为空！");
        AssertUtil.isTrue(StringUtil.isEmpty(customer.getNumber()),"联系电话不能为空！");
        AssertUtil.isTrue(StringUtil.isEmpty(customer.getAddress()),"联系地址不能为空！");



        AssertUtil.isTrue(!this.updateById(customer),"添加失败");

    }

    @Override
    public void deleteCustomer(Integer[] ids) {
        ArrayList<Customer> customers = new ArrayList<>();
        for (Integer id : ids) {
            Customer customer = this.getById(id);
            customer.setIsDel(1);
            customers.add(customer);

        }

        AssertUtil.isTrue(!this.updateBatchById(customers),"删除失败");

    }
}
